﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;

namespace AteneoLibri.Account
{
    public partial class Login : System.Web.UI.Page
    {

        protected void Page_PreInit(object sender, EventArgs e)
        {
            if (User.Identity.IsAuthenticated)
            {
                if (User.Identity.Name.Equals(System.Configuration.ConfigurationManager.AppSettings["AdminName"]))
                {
                    Page.MasterPageFile = "~/BackEnd/BackEndMasterPage.Master";
                }
                else
                {
                    Page.MasterPageFile = "~/Account/NewAccountMasterPage.Master";
                }
            }
        }
        
        protected void Page_Load(object sender, EventArgs e)
        {
            RegisterHyperLink.NavigateUrl = "Registration.aspx?ReturnUrl=" + HttpUtility.UrlEncode(Request.QueryString["ReturnUrl"]);
        }

        protected void LoginButton_Click(object sender, EventArgs e)
        {
            if (Page.IsValid)
            {
                string email = UserName.Text.Trim();
                string password = Password.Text.Trim();
                bool canProceed = false;

                bool AdminAuth = CheckAdminAuth(email, password);

                if (!AdminAuth)
                {
                    using (wsAteneoLibri.AteneoLibriServiceClient service = new wsAteneoLibri.AteneoLibriServiceClient())
                    {
                        string hashedPassword = Utility.Utility.hash(password);
                        AteneoLibriBusinessLogic.Entities.User loggedInUser = service.getUserByEmailAndPsw(email, hashedPassword);

                        if (loggedInUser != null)
                        {
                            if ((loggedInUser.VerifyRegistration != null && loggedInUser.VerifyRegistration.Value) && (loggedInUser.IsSuspended == null || !loggedInUser.IsSuspended.Value))
                            {
                                FormsAuthentication.SetAuthCookie(loggedInUser.Username, true);
                                Utility.HttpSessionManager.SetWebUser(loggedInUser);
                                canProceed = true;
                            }
                            else
                            {
                                lblErrorText.Text = "Devi completare la registrazione cliccando sul link che ti è stato inviato prima di poter procedere con il login.";
                                pnlLogInError.Visible = true;
                            }

                        }
                        else
                        {
                            lblErrorText.Text = "Credenziali non valide!";
                            pnlLogInError.Visible = true;
                        }
                        
                    }

                    if (canProceed)
                    {
                        string redirectUrl = HttpUtility.UrlEncode(Request.QueryString["ReturnUrl"]);
                        if (redirectUrl == null)
                            redirectUrl = "~/Account/Dashboard.aspx";

                        // TODO: spedizione email conferma registrazione
                        Response.Redirect(HttpUtility.UrlDecode(redirectUrl));
                    }
                }
                else
                {
                    AteneoLibriBusinessLogic.Entities.User admin = new AteneoLibriBusinessLogic.Entities.User();

                    admin.Username = System.Configuration.ConfigurationManager.AppSettings["AdminName"];
                    admin.Email = System.Configuration.ConfigurationManager.AppSettings["BEUsername"];
                    
                    FormsAuthentication.SetAuthCookie(admin.Username, true);
                    Utility.HttpSessionManager.SetWebUser(admin);
                    canProceed = true;

                    if (canProceed)
                    {
                        string redirectUrl = HttpUtility.UrlEncode(Request.QueryString["ReturnUrl"]);
                        // if (redirectUrl == null)
                        // overwrite standard redirect
                        redirectUrl = "~/BackEnd/BackEndDefault.aspx";

                        // TODO: spedizione email conferma registrazione
                        Response.Redirect(HttpUtility.UrlDecode(redirectUrl));
                    }
                }
                
            }
        }

        /// <summary>
        /// Authenticate Back-End user
        /// </summary>
        /// <param name="email"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        private bool CheckAdminAuth(string email, string password)
        {
            bool result = false;
            string BEUsername = System.Configuration.ConfigurationManager.AppSettings["BEUsername"];
            string BEPassword = System.Configuration.ConfigurationManager.AppSettings["BEPassword"];
            if (email.Equals(BEUsername) && password.Equals(BEPassword))
            {
                result = true;
            }
            return result;
        }

    }
}
